package com.anrongtec.zcpt.callback;

import android.app.Activity;
import android.app.ProgressDialog;
import android.support.annotation.Nullable;

import com.art.base.util.DialogUtil;
import com.lzy.okhttputils.request.BaseRequest;

import java.lang.reflect.Type;

import okhttp3.Call;
import okhttp3.Request;
import okhttp3.Response;

/**
 * ================================================ 作 者：廖子尧 版 本：1.0
 * 创建日期：2016/1/14 描 述：对于网络请求是否需要弹出进度对话框 修订历史：
 * ================================================
 */
public abstract class DialogCallback<T> extends JsonCallback<T> {

	private ProgressDialog dialog;

	private void initDialog(Activity activity, String msg) {
		dialog = DialogUtil.createLoadingDialog(activity, msg);
		// 网络请求前显示对话框
		if (dialog != null && !dialog.isShowing()) {
			dialog.show();
		}
	}

	public DialogCallback(Activity activity, Class<T> clazz, String msg) {
		super(clazz);
		initDialog(activity, msg);
	}

	public DialogCallback(Activity activity, Type type, String msg) {
		super(type);
		initDialog(activity, msg);
	}

	@Override
	public void onBefore(BaseRequest request) {
		super.onBefore(request);
		// // 网络请求前显示对话框
		// if (dialog != null && !dialog.isShowing()) {
		// dialog.show();
		// }
	}

	@Override
	public void onError(boolean isFromCache, Call call, Response response,
			Exception e) {
		super.onError(isFromCache, call, response, e);
		if (dialog != null && dialog.isShowing()) {
			dialog.cancel();
		}
	}

	@Override
	public void onResponse(boolean isFromCache, T arg1, Request arg2,
			Response response) {
		if (arg1 == null) {
			throw new NullPointerException("bean 解析失败");
		}
	}

	@Override
	public void onAfter(boolean isFromCache, @Nullable T t, Call call,
			@Nullable Response response, @Nullable Exception e) {
		if (dialog != null && dialog.isShowing()) {
			dialog.cancel();
		}
		super.onAfter(isFromCache, t, call, response, e);
		// 网络请求结束后关闭对话框
	}
}
